package com.hulu73.shiro.realm;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hulu73.shiro.dao.MenuDao;
import com.hulu73.shiro.dao.RoleDao;
import com.hulu73.shiro.dao.UserDao;
import com.hulu73.shiro.entity.UserEntity;

/**
 * 系统安全认证实现类
 * @author Administrator
 *
 */
@Service
public class SystemAuthorizingRealm extends AuthorizingRealm{
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private RoleDao roleDao;
	
	@Autowired
	private MenuDao menuDao;
	
	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken	usernamePasswordToken = (UsernamePasswordToken) token;
		String accessToken = (String) token.getPrincipal();
		String	userName=usernamePasswordToken.getUsername();
		UserEntity  user = userDao.getByLoginName(userName);
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());
		return	info;
		
	} 

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		UserEntity user = (UserEntity)principals.getPrimaryPrincipal();
        Long userId = user.getUserId();

        //用户权限列表
        Set<String> permsSetAll = menuDao.queryAllPerms(userId);
        
      //用户权限列表
        Set<String> permsSet = new HashSet<String>();
        for(String perms : permsSetAll){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
	}

	

}
